package com.platform.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.platform.annotation.SysLog;
import com.platform.entity.SysOssEntity;
import com.platform.entity.SysUserEntity;
import com.platform.oss.CloudStorageConfig;
import com.platform.oss.CloudStorageService;
import com.platform.oss.OSSFactory;
import com.platform.service.SysConfigService;
import com.platform.service.SysOssService;
import com.platform.utils.Base64Utils;
import com.platform.utils.Constant;
import com.platform.utils.PageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
import com.platform.utils.RRException;
import com.platform.utils.ShiroUtils;
import com.platform.validator.ValidatorUtils;
import com.platform.validator.group.AliyunGroup;
import com.platform.validator.group.QcloudGroup;
import com.platform.validator.group.QiniuGroup;

/**
 * 文件上传Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;

    private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;

    /**
     * 列表
     *
     * @param params 请求参数
     * @return R
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:oss:all")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<SysOssEntity> sysOssList = sysOssService.queryList(query);
        int total = sysOssService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(sysOssList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 获取云存储配置信息
     *
     * @return R
     */
    @RequestMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R config() {
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);
        return R.ok().put("config", config);
    }

    /**
     * 保存云存储配置信息
     *
     * @param config 配置信息
     * @return R
     */
    @SysLog("保存云存储配置信息")
    @RequestMapping("/saveConfig")
    @RequiresPermissions("sys:oss:all")
    public R saveConfig(@RequestBody CloudStorageConfig config) {
        //校验类型
        ValidatorUtils.validateEntity(config);

        if (config.getType() == Constant.CloudService.QINIU.getValue()) {
            //校验七牛数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        } else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
            //校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
            //校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        }
        sysConfigService.updateValueByKey(KEY, JSON.toJSONString(config));
        return R.ok();
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return R
     * @throws Exception 异常
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //上传文件
        String url = OSSFactory.build().upload(file);

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        sysOssService.save(ossEntity);

        R r = new R();
        r.put("url", url);
        r.put("link", url);
        return r;
    }
    
    /**
     * 上传文件
     *
     * @param file 文件
     * @return R
     * @throws Exception 异常
     */
    @RequestMapping("/upload/{fileType}/{objectType}/{objectId}")
    public R uploadObject(@PathVariable("objectType") String objectType,
    		@PathVariable("objectId") Integer objectId,@PathVariable("fileType") Integer fileType,
    		@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //上传文件
        String url = OSSFactory.build().upload(file);
        SysUserEntity currentUser = ShiroUtils.getUserEntity();

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        ossEntity.setCreateUserId(currentUser.getUserId().intValue());
        ossEntity.setFileName(file.getOriginalFilename());
        ossEntity.setFileType(fileType);
        ossEntity.setObjectId(objectId);
        ossEntity.setObjectType(objectType);
        ossEntity.setStatus(1);
        sysOssService.save(ossEntity);

        R r = new R();
        r.put("oss", ossEntity);
        return r;
    }
    /**
     * 上传文件
     *
     * @param file 文件
     * @return R
     * @throws Exception 异常
     */
    @RequestMapping( value="/uploadimgstr/{objectType}/{objectId}",method=RequestMethod.POST)
    public R upload(@PathVariable("objectType") String objectType,@PathVariable("objectId") Integer objectId,
    		@RequestParam  Map<String, Object> params) {
        if (params.get("base64url") == null) {
        	return R.error("图片不能为空！");
        }
        try {
            String [] d = params.get("base64url").toString().split("base64,");
            String suffix = null;
            String dataPrix = d[0];
            if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//编码的jpeg图片数据
                suffix = ".jpg";
            } else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//编码的icon图片数据
                suffix = ".ico";
            } else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//编码的gif图片数据
                suffix = ".gif";
            } else if("data:image/png;".equalsIgnoreCase(dataPrix)){//编码的png图片数据
                suffix = ".png";
            }else{
        		return R.error("上传图片格式不合法！");
            }
            
	    	byte[] b = Base64Utils.Base64ToByte(d[1]);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			
	        SysUserEntity currentUser = ShiroUtils.getUserEntity();
	        String fileName = CloudStorageService.getPath("")+ suffix;
	        //上传文件
	        String url = OSSFactory.build()
	        		.upload(b,fileName);
	        //保存文件信息
	        SysOssEntity ossEntity = new SysOssEntity();
	        ossEntity.setUrl(url);
	        ossEntity.setCreateDate(new Date());
	        ossEntity.setCreateUserId(currentUser.getUserId().intValue());
	        ossEntity.setFileName(fileName);
	        ossEntity.setFileType(0);
	        ossEntity.setObjectId(objectId);
	        ossEntity.setObjectType(objectType);
	        ossEntity.setStatus(1);
	        sysOssService.save(ossEntity);
	        return R.ok().put("attachment", ossEntity);
        }catch(Exception e) {
        	logger.error("upload", e);
        	return R.error("系统异常！"+e.getMessage());
        }
    }
    
    @RequestMapping("/list/{objectType}/{objectId}")
    public R listByObjectTypeId(@PathVariable("objectType") String objectType,@PathVariable("objectId") Integer objectId) {
    	Map<String, Object> params = new HashMap<String,Object>();
    	params.put("objectId", objectId);
    	params.put("objectType", objectType);
    	params.put("status", 1);

        List<SysOssEntity> sysOsses = sysOssService.queryList(params);
        List<SysOssEntity> files = new ArrayList<SysOssEntity>();
        List<SysOssEntity> imgs = new ArrayList<SysOssEntity>();
        if(sysOsses != null && sysOsses.size()>0) {
            for(SysOssEntity attachment:sysOsses) {
            	if(attachment.getFileType() == 0 ) {
            		files.add(attachment);
            	}else if(attachment.getFileType() == 1) {
            		imgs.add(attachment);
            	}
            }
        }
        return R.ok().put("files", files).put("imgs", imgs).put("allOss", sysOsses);    
    }

    /**
     * 删除图片
     *
     * @param ids 主键集
     * @return R
     */
    @SysLog("删除图片")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:oss:all")
    public R delete(@RequestBody Long[] ids) {
        sysOssService.deleteBatch(ids);
        return R.ok();
    }
    /**
     * 删除图片
     *
     * @param ids 主键集
     * @return R
     */
    @SysLog("删除图片")
    @RequestMapping("/delete/{id}")
    @RequiresPermissions("sys:oss:all")
    public R deleteById(@PathVariable("id") Long id) {
        sysOssService.delete(id);
        return R.ok();
    }
    /**
     * 查询所有列表
     *
     * @param params 请求参数
     * @return R
     */
    @RequestMapping("/queryAll")
    public List<String> queryAll(@RequestParam Map<String, Object> params) {
        //查询列表数据
        List<SysOssEntity> sysOssList = sysOssService.queryList(params);

        List<String> list = new ArrayList<>();
        if (null != sysOssList && sysOssList.size() > 0) {
            for (SysOssEntity item : sysOssList) {
                list.add(item.getUrl());
            }
        }
        return list;
    }
}
